<template>
  <div class="record-wall">
    <el-row :gutter="20">
      <!-- 左侧记录墙 -->
      <el-col :span="16">
        <el-card shadow="hover" class="wall-card">
          <template #header>
            <div class="card-header">
              <span>学习记录墙</span>
              <el-button-group>
                <el-button type="primary" @click="createRecord">
                  <el-icon>
                    <Plus />
                  </el-icon>
                  发布记录
                </el-button>
                <el-button @click="toggleView">
                  <el-icon>
                    <Grid />
                  </el-icon>
                  切换视图
                </el-button>
              </el-button-group>
            </div>
          </template>

          <!-- 记录筛选 -->
          <div class="record-filter">
            <el-input v-model="searchText" placeholder="搜索记录" class="search-input">
              <template #prefix>
                <el-icon>
                  <Search />
                </el-icon>
              </template>
            </el-input>
            <el-select v-model="selectedTag" placeholder="选择标签" clearable>
              <el-option v-for="tag in stats.hot_tags" :key="tag.name" :label="tag.name" :value="tag.name" />
            </el-select>
            <el-radio-group v-model="timeRange" size="small">
              <el-radio-button label="week">本周</el-radio-button>
              <el-radio-button label="month">本月</el-radio-button>
              <el-radio-button label="all">全部</el-radio-button>
            </el-radio-group>
          </div>

          <!-- 记录列表 -->
          <el-scrollbar height="650px">
            <div class="record-list-container">
              <RecordList :records="filteredRecords" :is-grid-view="isGridView" :current-user-id="currentUserId"
                @edit="editRecord" @delete="deleteRecord" @like="likeRecord" @comment="handleComment"
                @loadComments="loadComments" />
            </div>
          </el-scrollbar>
        </el-card>
      </el-col>

      <!-- 右侧统计和排行 -->
      <el-col :span="8">
        <!-- 个人统计 -->
        <el-card shadow="hover" class="stats-card">
          <template #header>
            <div class="card-header">
              <span>学习统计</span>
              <el-tag type="success">{{ totalHours }}小时</el-tag>
            </div>
          </template>

          <div class="stats-content">
            <el-row :gutter="20">
              <el-col :span="8" v-for="stat in studyStats" :key="stat.label">
                <div class="stat-box">
                  <div class="stat-value">{{ stat.value }}</div>
                  <div class="stat-label">{{ stat.label }}</div>
                </div>
              </el-col>
            </el-row>

            <!-- 学习趋势图 -->
            <div class="trend-chart" ref="timeChart"></div>
          </div>
        </el-card>

        <!-- 标签云 -->
        <el-card shadow="hover" class="tags-card">
          <template #header>
            <div class="card-header">
              <span>热门标签</span>
            </div>
          </template>

          <div class="tag-cloud">
            <el-tag v-for="tag in stats.hot_tags" :key="tag.name" :type="tag.count > 5 ? 'success' : ''"
              class="tag-item" @click="selectedTag = tag.name">
              {{ tag.name }}
              <span class="tag-count">({{ tag.count }})</span>
            </el-tag>
          </div>
        </el-card>

        <!-- 排行榜 -->
        <el-card shadow="hover" class="ranking-card">
          <template #header>
            <div class="card-header">
              <span>学习达人</span>
            </div>
          </template>

          <div class="ranking-list">
            <div v-for="(user, index) in stats.top_learners" :key="user.id" class="ranking-item">
              <div :class="['rank-index', index < 3 ? 'top-three' : '']">
                {{ index + 1 }}
              </div>
              <el-avatar :src="generateAvatar(user.username)" />
              <div class="user-info">
                <span>{{ user.username }}</span>
                <span class="study-time">
                  {{ user.study_hours }}
                  <span class="unit">小时</span>
                </span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 发布记录对话框 -->
    <el-dialog v-model="dialogVisible" title="发布记录" width="60%">
      <el-form :model="recordForm" label-width="80px">
        <el-form-item label="内容">
          <div class="editor-container">
            <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
              mode="default" />
              <Editor
              style="height: 300px; overflow-y: hidden;"
              :key="editorKey" 
              v-model="recordForm.content"
              :defaultConfig="editorConfig"
              mode="default"
              @onCreated="handleCreated"
            />
          </div>
        </el-form-item>
        <el-form-item label="标签">
          <el-select v-model="recordForm.tags" multiple placeholder="选择标签">
            <el-option v-for="tag in stats.hot_tags" :key="tag.name" :label="tag.name" :value="tag.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="学习时长">
          <el-input-number v-model="recordForm.duration" :min="0" :step="0.5" />
          <span class="unit">小时</span>
        </el-form-item>
        <el-form-item label="自评分数">
          <el-rate v-model="recordForm.score" :max="5" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="submitRecord">发布</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 评论对话框 -->
    <el-dialog v-model="commentDialogVisible" title="评论" width="500px">
      <div class="comment-list">
        <div v-for="comment in comments" :key="comment.id" class="comment-item">
          <el-avatar :size="32" :src="comment.avatar" />
          <div class="comment-content">
            <div class="comment-user">{{ comment.username }}</div>
            <div class="comment-text">{{ comment.content }}</div>
            <div class="comment-time">{{ comment.created_at }}</div>
          </div>
        </div>
        <el-empty v-if="!comments.length" description="暂无评论" />
      </div>
      <div class="comment-input">
        <el-input v-model="newComment" type="textarea" :rows="2" placeholder="写下你的评论..." />
        <el-button type="primary" @click="submitComment">发表评论</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, shallowRef, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Grid, Search } from '@element-plus/icons-vue'
import { wallApi } from '@/api/wall'
import * as echarts from 'echarts'
import RecordList from '@/components/RecordList.vue'
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import axios from 'axios'

// 基础数据
const records = ref([])
const stats = ref({
  user_stats: {},
  hot_tags: [],
  top_learners: [],
  study_trend: []
})
const searchText = ref('')
const selectedTag = ref('')
const timeRange = ref('all')
const isGridView = ref(false)
const dialogVisible = ref(false)
const currentUserId = ref(localStorage.getItem('userId'))

// 新记录表单
const recordForm = ref({
  content: '',
  tags: [],
  duration: 0,
  score: 0
})

// 获取记录列表
const fetchRecords = async () => {
  try {
    const params = {
      search: searchText.value,
      tag: selectedTag.value,
      range: timeRange.value
    }
    const response = await wallApi.getPosts(params)
    records.value = response
  } catch (error) {
    console.error('获取记录失败:', error)
    ElMessage.error('获取记录失败')
  }
}

// 获取统计数据
const fetchStats = async () => {
  try {
    const response = await wallApi.getStats(currentUserId.value)
    stats.value = response
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败')
  }
}

// 创建记录
const createRecord = () => {
  dialogVisible.value = true
}

// 切换视图
const toggleView = () => {
  isGridView.value = !isGridView.value
}

// 编辑器相关
const editorRef = shallowRef()
const toolbarConfig = {
  excludeKeys: [
    'uploadVideo',
    'insertTable',
    'group-video',
    'insertTable',
    'codeBlock',
    'fullScreen'
  ]
}
const editorConfig = {
  placeholder: '分享你的学习心得...',
  MENU_CONF: {
    uploadImage: {
      server: '/api/wall/upload-image/',
      fieldName: 'image',
      maxFileSize: 5 * 1024 * 1024, // 5MB
      maxNumberOfFiles: 10,
      allowedFileTypes: ['image/*'],
      customInsert(res, insertFn) {
        if (res.errno === 0) {
          // 插入图片
          insertFn(res.data.url, res.data.alt, res.data.href)
        } else {
          ElMessage.error(res.message || '图片上传失败')
        }
      }
    }
  }
}

// 编辑器创建完成时的回调
const handleCreated = (editor) => {
  editorRef.value = editor
}

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false
  // 重置表单
  setTimeout(() => {
    recordForm.value = {
      content: '',
      tags: [],
      duration: 0,
      score: 0
    }
  }, 200)
}

// 组件销毁时销毁编辑器
onBeforeUnmount(() => {
  if (editorRef.value) {
    editorRef.value.destroy()
  }
})

// 修改提交记录的方法
const submitRecord = async () => {
  try {
    // 从编辑器获取 HTML 内容
    const content = editorRef.value?.getHtml()

    if (!content) {
      ElMessage.warning('请输入内容')
      return
    }

    const formData = new FormData()
    // 使用编辑器的 HTML 内容
    formData.append('content', content)
    formData.append('user', currentUserId.value)
    formData.append('duration', recordForm.value.duration || 0)
    formData.append('score', recordForm.value.score || 0)
    formData.append('user_id', localStorage.getItem('userId'))

    // 确保 tags 是数组
    if (Array.isArray(recordForm.value.tags)) {
      formData.append('tags', JSON.stringify(recordForm.value.tags))
    } else {
      formData.append('tags', '[]')
    }

    // 如果有图片，添加图片
    if (recordForm.value.image) {
      formData.append('image', recordForm.value.image)
    }

    console.log('发送的数据:', {
      content: content,  // 打印实际发送的内容
      user: currentUserId.value,
      duration: recordForm.value.duration,
      score: recordForm.value.score,
      tags: recordForm.value.tags
    })

    await axios({
      method: 'POST',
      url: '/api/wall/posts/',  // 替换为实际的发布记录的 API URL
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    ElMessage.success('发布成功')
    // 先关闭对话框再刷新数据
    closeDialog() // 先执行关闭
    await fetchRecords() // 后执行数据刷新
  } catch (error) {
    console.error('发布失败:', error.response?.data || error)
    if (error.response?.data) {
      const errors = Object.values(error.response.data).flat()
      ElMessage.error(errors[0] || '发布失败')
    } else {
      ElMessage.error('发布失败')
    }
  }
}

// 监听时间范围变化
watch(timeRange, () => {
  fetchRecords()
})

// 监听搜索和标签变化
watch([searchText, selectedTag], () => {
  fetchRecords()
})

// 计算过滤后的记录
const filteredRecords = computed(() => {
  let result = records.value

  if (searchText.value) {
    result = result.filter(record =>
      record.content.toLowerCase().includes(searchText.value.toLowerCase()) ||
      record.tags.some(tag => tag.toLowerCase().includes(searchText.value.toLowerCase()))
    )
  }

  if (selectedTag.value) {
    result = result.filter(record =>
      record.tags.includes(selectedTag.value)
    )
  }

  return result
})

// 生成头像
const generateAvatar = (username) => {
  if (!username) return ''
  return `https://api.dicebear.com/7.x/avataaars/svg?seed=${username}`
}

// 评论相关
const commentDialogVisible = ref(false)
const currentRecord = ref(null)
const comments = ref([])
const newComment = ref('')

// 加载评论
const loadComments = async (record) => {
  try {
    const comments = await wallApi.getComments(record.id)
    record.commentList = comments.map(comment => ({
      ...comment,
      time: formatDateTime(comment.created_at)
    }))
  } catch (error) {
    console.error('获取评论失败:', error)
    ElMessage.error('获取评论失败')
  }
}

// 提交评论
const handleComment = async ({ record, content }) => {
  try {
    await wallApi.addComment({
      post: record.id,
      content: content,
      user: parseInt(currentUserId.value)
    })

    // 重新加载评论
    await loadComments(record)

    // 更新评论数
    record.comments_count = (record.comments_count || 0) + 1

    ElMessage.success('评论成功')
  } catch (error) {
    console.error('评论失败:', error)
    ElMessage.error('评论失败')
  }
}

// 处理点赞
const likeRecord = async (record) => {
  try {
    const { liked, likes_count } = await wallApi.likePost(record.id)
    record.liked = liked
    record.likes_count = likes_count
    ElMessage.success(liked ? '点赞成功' : '已取消点赞')
  } catch (error) {
    console.error('点赞失败:', error)
    ElMessage.error('点赞失败')
  }
}

// 格式化日期时间
const formatDateTime = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
}

// 计算属性
const studyStats = computed(() => [
  { label: '总记录', value: stats.value.user_stats.total_posts },
  { label: '总时长', value: stats.value.user_stats.total_hours },
  { label: '平均分数', value: stats.value.user_stats.avg_score?.toFixed(1) || 0 },
  { label: '获赞数', value: stats.value.user_stats.total_likes },
  { label: '学习天数', value: stats.value.user_stats.study_days }
])

const totalHours = computed(() => stats.value.user_stats.total_hours || 0)

// 图表相关
const timeChart = ref(null)
let chart = null

// 初始化图表
const initChart = () => {
  if (!timeChart.value) return

  chart = echarts.init(timeChart.value)
  updateChart()

  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
}

// 更新图表数据
const updateChart = () => {
  if (!chart) return

  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        return `${params[0].name}<br/>学习时长：${params[0].value}小时`
      }
    },
    xAxis: {
      type: 'category',
      data: stats.value.study_trend.map(item => item.date),
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '学习时长(小时)'
    },
    series: [{
      data: stats.value.study_trend.map(item => item.duration),
      type: 'line',
      smooth: true,
      areaStyle: {
        opacity: 0.3
      },
      itemStyle: {
        color: '#409EFF'
      }
    }]
  }

  chart.setOption(option)
}

// 处理窗口大小变化
const handleResize = () => {
  chart?.resize()
}

// 监听数据变化更新图表
watch(() => stats.value.study_trend, () => {
  updateChart()
}, { deep: true })

// 组件挂载时初始化图表
onMounted(() => {
  initChart()
})

onBeforeUnmount(() => {
  if (editorRef.value && !editorRef.value.isDestroyed) {
    editorRef.value.destroy()
  }
  window.removeEventListener('resize', handleResize)
})

// 在组件挂载时获取数据
onMounted(async () => {
  await fetchRecords()
  await fetchStats()
})
</script>

<style scoped>
.record-wall {
  padding: 20px;
}

.wall-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.record-filter {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
}

.search-input {
  width: 240px;
}

.record-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.record-list.grid-view {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.record-item {
  transition: all 0.3s;
}

.record-item:hover {
  transform: translateY(-2px);
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-meta {
  display: flex;
  flex-direction: column;
}

.username {
  font-weight: 500;
}

.time {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.record-content {
  margin-bottom: 16px;
}

.record-text {
  margin-bottom: 12px;
  line-height: 1.6;
}

.record-images {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;
  margin-bottom: 12px;
}

.record-images :deep(.el-image) {
  width: 100%;
  height: 0;
  padding-bottom: 100%;
  border-radius: 4px;
  overflow: hidden;
}

.record-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.record-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid var(--el-border-color-lighter);
}

.record-stats {
  display: flex;
  gap: 16px;
  color: var(--el-text-color-secondary);
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.record-actions {
  display: flex;
  gap: 16px;
}

.stats-card,
.tags-card,
.ranking-card {
  margin-bottom: 20px;
}

.stats-content {
  padding: 20px 0;
}

.stat-box {
  text-align: center;
  padding: 12px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: var(--el-color-primary);
  margin-bottom: 4px;
}

.stat-label {
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.trend-chart {
  margin-top: 20px;
  height: 300px;
  width: 100%;
}

.tag-cloud {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag-item {
  cursor: pointer;
}

.tag-count {
  margin-left: 4px;
  font-size: 12px;
  opacity: 0.8;
}

.ranking-list {
  display: flex;
  flex-direction: column;
}

.ranking-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.ranking-item:last-child {
  border-bottom: none;
}

.rank-index {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-regular);
  font-weight: bold;
}

.rank-index.top-three {
  background: var(--el-color-primary);
  color: white;
}

.user-info {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.study-time {
  color: var(--el-color-primary);
  font-weight: 500;
}

.unit {
  margin-left: 8px;
  color: var(--el-text-color-secondary);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .el-col {
    width: 100% !important;
  }

  .record-list.grid-view {
    grid-template-columns: 1fr;
  }

  .record-filter {
    flex-direction: column;
  }

  .search-input {
    width: 100%;
  }
}

/* 编辑器样式 */
.w-e-text-container {
  min-height: 300px !important;
}

.record-list-container {
  padding: 16px;
}

.chart {
  width: 100%;
  height: 100%;
}

.comment-list {
  max-height: 300px;
  overflow-y: auto;
  margin-bottom: 16px;
}

.comment-item {
  display: flex;
  gap: 12px;
  padding: 12px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.comment-content {
  flex: 1;
}

.comment-user {
  font-weight: 500;
  margin-bottom: 4px;
}

.comment-text {
  color: var(--el-text-color-regular);
}

.comment-time {
  color: var(--el-text-color-secondary);
  font-size: 12px;
  margin-top: 4px;
}

.comment-input {
  display: flex;
  gap: 12px;
  align-items: flex-start;
}

.editor-container {
  border: 1px solid var(--el-border-color-light);
  border-radius: 4px;
}

:deep(.w-e-text-container) {
  min-height: 300px !important;
}

:deep(.w-e-toolbar) {
  border-bottom: 1px solid var(--el-border-color-light) !important;
}

:deep(.w-e-text-placeholder) {
  color: var(--el-text-color-placeholder);
}
</style>